<?php
if (!defined('ZZQSS')){
	die("Access Denied");
}

/*******************
*membarclass 類，處理用戶相關操作,包含ucenter
*reg() 註冊
*login()登錄
*checkuname()檢測用戶名
*checkemail()檢測郵箱
*checkuser()檢測用戶和密碼
*
*
*quit()退出操作
*/
class memberclass
{
	var $db;
	var $table;
	var $cookietime;
	var $ucsynlogin;		//uc同步信息，登錄或者退出
	var $notallow=array('user','manger');//禁止註冊用戶名
	function __construct()
	{	//設置全局變量
		global $db,$tablepre,$cfg_login_time;
		$this->db=$db;
		$this->table=$tablepre."users";
		$this->cookietime=time()+$cfg_login_time;
		if(!$cookietime)$this->cookietime=time()+3600; //cookie默認時間
	}
	function memberclass()
	{
		$this->__construct();
	}
	//用戶註冊操作
	function reg($uname,$password,$email,$uarray=array())
	{	
		global $cfg_reg_score;//註冊送積分
		$timestamp=time();
		$ckname=$this->checkuname($uname,true);
		$ckmail=$this->checkemail($email,true);
		if($ckname=="OK" && $ckmail=="OK")
		{
			$pwd=md5(md5($password));//加密方式 兩次MD5
			#api{{
			if(defined('UC_API') && @include_once ROOT_PATH.'/uc_client/client.php')
			{	
				$uid = uc_user_register($uname, $password, $email);
				if($uid <= 0)
				{
					if($uid == -1)
					{
						return "用戶名不合法";
					}
					elseif($uid == -2)
					{
						return "包含要允許註冊的詞語";
					}
					elseif($uid == -3)
					{
						return "你指定的用戶名 {$uname} 已存在，請使用別的用戶名";
					}
					elseif($uid == -5)
					{
						return "你使用的Email 不允許註冊";
					}
					elseif($uid == -6)
					{
						return "你使用的Email已經被另一帳號註冊，請使其它帳號";
					}
					else
					{
						return "注刪失敗";
					}
				}
				else
				{
					//插入本地數據庫操作	
					$uarray['uid']=$uid;
					$uarray['pwd']=$pwd;
					$uarray['uname']=$uname;
					$uarray['email']=$email;
					$uarray['addtime']=$timestamp;
					$uarray['lastlogin']=$timestamp;
					$uarray['score']=$cfg_reg_score;//註冊送積分
					if(is_numeric(inserttable($this->table, $uarray,1))){
						$this->ucsynlogin = uc_user_synlogin($uid);
						$auth=$uid."\t".$uname."\t".$pwd;
						set_cookie('loginauth',cookie_authcode($auth,'ENCODE'));
						return 'OK';
					}
				}
			}else {
			#/aip}}	
			//不是ucenter狀態
			//插入數據庫用戶
			$this->db->query("INSERT INTO `$this->table`(uname,email,pwd,score,money,addtime,lastlogin) values('$uname','$email','$pwd','$cfg_reg_score',0,$timestamp,$timestamp)");	
			$uid=$this->db->insert_id();
			$auth=$uid."\t".$uname."\t".$pwd;
			set_cookie('loginauth',cookie_authcode($auth,'ENCODE'),$this->cookietime);	
			return 'OK';
			}
			
		}else 
		{
			$errormsg="";			
			if($ckname!='OK')$errormsg.=$ckname;
			if($ckmail!='OK')$errormsg.=$ckmail;
			return $errormsg;
			
		}

	}
	//用戶登錄操作
	function login($uname,$pwd)
	{
		global $timestamp;
		$rs=$this->CheckUser($uname,$pwd);//本地驗證通過 -1格式錯誤
		if($rs!=-1)
		{
			#api{{
			if(defined('UC_API') && @include_once ROOT_PATH.'/uc_client/client.php')
			{
				//檢查帳號UC
				list($uid, $username, $password, $email) = uc_user_login($uname, $pwd);
				if($uid > 0) {//uc登錄成功
					$password = md5(md5($password));
					if($rs == -3) {
						//本地數據庫不存在自動插入一個用戶
						$this->db->query("INSERT INTO `$this->table`(uid,uname,email,pwd,score,money,addtime,lastlogin) values($uid,'$username','$email','$password',0,0,$timestamp,$timestamp)");
					
					}else if ($rs==-2) {
						$this->db->query("update `$this->table` SET pwd='{$password}' WHERE uname='$username'");
					} 		
				$rs = 1;
				//設置cookie
				$auth=$uid."\t".$username."\t".$password;
				set_cookie('loginauth',cookie_authcode($auth,'ENCODE'),$this->cookietime);	
				//生成同步登錄的代碼
				$this->ucsynlogin = uc_user_synlogin($uid);
				return 'OK';
				}else if($uid == -1)
				{
					
					//當UC不存在 系統存在,就註冊一個
					if($rs==1) {
						$row = $this->db->fetch_first("Select * From `$this->table` where uname like '$uname' ");
						$uid = uc_user_register($uname, $pwd, $row['email']);
						//設置cookie
						$auth=$uid."\t".$uname."\t".md5(md5($pwd));
						set_cookie('loginauth',cookie_authcode($auth,'ENCODE'),$this->cookietime);	
						if($uid > 0) $ucsynlogin = uc_user_synlogin($uid);
						return 'OK';
					}elseif ($rs==-3){
						return '用戶名和密碼不存在';
					}else {
						return '密碼錯誤';
					}
					
				} else {
					$rs = -2;//密碼錯誤
					return '密碼錯誤';
				}
	
			}else if ($rs==1) {
			#/aip}}	
				//非ucenter模式下用戶登錄操作
				$row = $this->db->fetch_first("Select * From `$this->table` where uname like '$uname' ");
				//設置cookie記錄
				$auth=$row['uid']."\t".$uname."\t".$row['pwd'];
				set_cookie('loginauth',cookie_authcode($auth,'ENCODE'),$this->cookietime);
				$this->db->query("update `$this->table` SET lastlogin={$timestamp} WHERE uname='$uname'");
				return 'OK';
			}else {
				if($rs==-2)return "用戶名或者密碼錯誤";
				else return "用戶不存在";
			}
		}
		else
		{
			return "數據格式錯誤";
		}
	}
	
	//quit退出系統
	function quit()
	{
		#api{{
		if(defined('UC_API') && @include_once ROOT_PATH.'/uc_client/client.php')
		{
		$this->ucsynlogin = uc_user_synlogout();
		}
		#/aip}}
		set_cookie('loginauth','',- $this->cookietime);//設置cookie過期
		return true;
	}
	//修改資料
	function edit($uname,$email,$oldpassword,$password="",$garray="",$address)
	{
		if($this->checkemail($email,false)=='OK' && !empty($uname)){
			if(!empty($password)){
				#api{{
				if(defined('UC_API') && @include_once ROOT_PATH.'/uc_client/client.php')
				{
					$ucresult = uc_user_edit($uname,$oldpassword, $password, $email,1);
					if($ucresult<0){
						if($ucresult == -1) {
							return '舊密碼不正確';
						} elseif($ucresult == -4) {
							return  'Email 格式有誤';
						} elseif($ucresult == -5) {
							return  'Email 不允許註冊';
						} elseif($ucresult == -6) {
							return  '該 Email 已經被註冊';
						}
					}
				}
				#/aip}} 
				$pwd=md5(md5($password));
				$this->db->query("update `$this->table` SET pwd= '{$pwd}'  WHERE uname='$uname' and email='$email'");		
			}
			if(is_array($garray)){
				//更新數據庫操作
				$wheresqlarr=" uname='{$uname}'";
				updatetable($this->table,$garray, $wheresqlarr);				
			}
			return "OK";
	
		}else 
		{
			return "email格式錯誤";
		}
		
	}
	//刪除用戶
	function del($uid)
	{
		if(is_numeric($uid))
		{
			$this->db->query("delete from `$this->table` where uid='{$uid}'");
			return true;
		}else 
		{
			return false;
		}
		
	}
	//檢測本地數據庫用戶名密碼 返回1正常 負數出錯
	function CheckUser($uname,$password)
	{
		if($this->checkuname($uname,false)!='OK')return -1;//格式錯誤
		$row = $this->db->fetch_first("Select * From `$this->table` where uname like '$uname' ");
		if(is_array($row))
		{
			if(md5(md5($password)) != $row['pwd'])
			{
				return -2;//密碼錯誤
			}else 
			{
				return 1;//通過檢測
			}
		
		}else 
		{
			return -3;//用戶名不存在
		}
	}
	
	//判斷用戶名是否重複
	function checkuname($uname,$ckhas=true)
	{
		if(!preg_match("/^[a-zA-Z0-9_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]+$/", $uname))
		{
			return '用戶名格式錯誤';
		}
		if ( 50 <= strlen($uname) || strlen($uname) < 2 )
		{
			return '用戶名長度不合法';
		}
		if($ckhas)
		{	#api{{
			if(defined('UC_API') && @include_once ROOT_PATH.'/uc_client/client.php')
			{
				$ucresult = uc_user_checkname($uname);
				
				if($ucresult > 0)
				{
					return 'OK';
				}
				elseif($ucresult == -1)
				{
					return "用戶名不合法";
				}
				elseif($ucresult == -2)
				{
					return "包含不允許註冊的詞語";
				}
				elseif($ucresult == -3)
				{
					return "用戶名已經存在";
				}
			}else {
			#/aip}}
			$row = $this->db->fetch_first("Select * From `$this->table` where uname like '$uname' ");
			if(is_array($row)) return "用戶名已經存在";
			}
		}
		return 'OK';
	}
	//檢測email
	function checkemail($email,$ckhas=true)
	{
		if(!isemail($email))return "Email 格式有誤";
		if($ckhas){
			#api{{
		if(defined('UC_API') && @include_once ROOT_PATH.'/uc_client/client.php')
		{
			$ucresult = uc_user_checkemail($email);
			if($ucresult > 0) {
				return "OK";
			} elseif($ucresult == -4) {
				return "Email 格式有誤";
			} elseif($ucresult == -5) {
				return "Email 不允許註冊";
			} elseif($ucresult == -6) {
				return "該 Email 已經被註冊";
			}
			exit();
		}else {
		#/aip}}		
			$row = $this->db->fetch_first("Select * From `$this->table` where email like '$email' ");
			if(is_array($row)) return "該 Email 已經被註冊";
			return "OK";
		}
		}
		return 'OK';

	}
	
	//用戶積分操作
	function scoreedit($uname,$num=0)
	{
		if(!empty($uname) && $num==0)
		{
			$row = $this->db->fetch_first("Select score From `$this->table` where uname like '$uname' ");
			return $row['score'];
		}elseif (!empty($uname) && $num!=0 && is_numeric($num)) {
			$this->db->query("update `$this->table` SET score= score+{$num} WHERE uname='$uname'");
			return true;
		}else {
			return false;
		}
		
	}
	//用戶賬戶余額操作
	/*
	 * $uname 姓名
	 * $num   購物金
	 * $note  備註
	 */
	function moneyedit($uname,$num=0,$note="")
	{
		if(!empty($uname) && $num==0)
		{
			$row = $this->db->fetch_first("Select money From `$this->table` where uname like '$uname' ");
			return $row['money'];
		}elseif (!empty($uname) && $num!=0 && is_numeric($num)) {
			$this->db->query("update `$this->table` SET money= money+{$num} WHERE uname='$uname'");
			//寫入日誌文件
			if($num>0)$edittype="增加";else $edittype="減去";
			$datastr=date('Y-m-d h:i:s');
			$log=$datastr.'|用戶名：'.$uname.'|'.$edittype.'|金額：'.$num.'|說明'.$note;
			@writelog('money_edit', $log);
			//增加寫入文件日誌操作！記錄每次用戶錢幣改動
			return true;
		}else {
			return false;
		}

	}
	/**
	 * 獲取一條信息
	 *
	 * @param unknown_type $oid
	 * @return unknown
	 */
	function getone($uid){
		if (is_numeric($uid)) {
			$uid=$this->db->result_first("Select uname From `$this->table` WHERE uid='{$uid}'");
		}
		$gpdata=$this->getdata(1,"uname='{$uid}'");
		$value=$gpdata[0];
		return $value;
		
	}
	/**
	 * 獲取一條信息
	 *
	 * @param unknown_type $oid
	 * @return unknown
	 */
	function getonebyemail($email){
		if (isemail($email)) {
			$uid=$this->db->result_first("Select uname From `$this->table` WHERE email='{$email}'");
		}
		if (!empty($uid)) {
			$gpdata=$this->getdata(1,"uname='{$uid}'");
			$value=$gpdata[0];
			return $value;
		}else {
			return false;
		}
	}
	
	/**
	 * 獲取數據數組
	 *
	 * @param string $limit
	 * @param string $where
	 * @param string $orderby
	 * @return array
	 */
	function getdata($limit="",$where="",$orderby="")
	{
		$tempdata=array();
		if(!empty($limit))$limit=" limit $limit ";
		if(!empty($where))$where=" where $where ";
		if(!empty($orderby))$orderby=" order by $orderby ";else $orderby=" order by uid desc";

		$sql="select * from {$this->table}{$where}{$orderby}{$limit}";
		$query =$this->db->query($sql);
		while($value = $this->db->fetch_array($query)) {
			//此處可進行數據整理
			$tempdata[]=$value;
		}
		return $tempdata;
	}
	function getcount($where=""){
		if(!empty($where))$where=" where $where";
		$count= $this->db->result_first("Select count(*) From `$this->table` $where");
		return $count;
	
	}	
	
	
}

?>